const express = require('express');
const router = express.Router();
const error = require("./error");
const util = require("./util");
// mongo
const getTable = require('./mongo').getTable;
const userCenter = getTable("userCenter");
const chat = getTable("chat");

// filter
const FILTER = {
    password: 0,
    __v: 0
}

// findAllUser
const findAllUser = () => {
    let users = {};
    userCenter.find({}, FILTER, (err, doc) => {
        doc.forEach(v => {
        users[v._id] = {
            name: v.userName,
            tx: v.tx,
        }
        });
    });
    return users;
};

router.post('/login', (req, res) => {
    const { userName, password } = req.body;

    userCenter.findOne({userCenter, password: util.pwdFormat(password)}, (err, doc) => {
        if(doc){
            const { userName, userType, id } = doc,
                  info = {userName, userType, id};

            req.session.userInfo = info;
            util.rtData(res, 200, info);
        }else{
            util.rtData(res, 1003, {});
        }
    });
});

router.get('/userInfo', (req, res) => {
    if(util.auth(req,res)){
        const { userName } = (req.session.userInfo.info || req.session.userInfo);
        userCenter.findOne({userName}, (err, doc) => {
            if(doc){
                const { id, userName, userType, jj, zw, m, tx } = doc,
                      send = { id, userName, userType, detail:{ jj, zw, m, tx } };
                util.rtData(res, 200, send);
            } else {
                util.delSession(req);
                util.rtData(res, 1004);
            }
        });
    }
});

router.get('/isLogin', (req, res) => {
    req.session.userInfo ? util.rtData(res, 200) : util.rtData(res, 1002);
});

router.post('/register', (req, res) => {
    // format data
    let saveData = req.body;
    saveData = Object.assign({}, saveData, {password: util.pwdFormat(saveData.password)});
    // write to mongo
    userCenter.findOne({userName: saveData.userName}, (err, doc) => {
        if(!doc){
            userCenter.create(saveData, (err, doc) => {
                let r = {},
                    code = 0;
                if(!err){
                    code = 200;
                }else{
                    code = 1001;
                }
        
                r = {
                    code,
                    msg: error[code],
                    info:{
                        id: code === 200 ? doc.id : undefined,
                        userName: saveData.userName,
                        userType: saveData.userType
                    }
                };
                
                // save to session
                req.session.userInfo = r;
        
                res.json(r);
            });
        }else{
            const code = 1001;
            res.json({
                code,
                msg: error[code]
            });
        }
    });
});

router.post('/finish', (req, res) => {
    if(util.auth(req, res)){
        const { _id, ...up } = req.body;
        userCenter.update({_id}, {$set: up}, (err, doc) => {
            if(!err){
                if(doc.nModified > 0){
                    util.rtData(res, 200, up);
                }else{
                    util.rtData(res, 1006);
                }
            }else{
                util.rtData(res, 1005);
            }
        });
    }
});

router.get('/getUserList', (req, res) => {
    if(util.auth(req,res)){
        userCenter.find(req.query, FILTER, (err, doc) => {
            if(!err){
                util.rtData(res, 200, doc);
            } else {
                util.rtData(res, 200, []);
            }
        });
    }
});

router.get('/logout', (req, res) => {
    util.delSession(req);
    res.clearCookie('session_id');
    return util.rtData(res, 1004);
});

router.get('/getUserMsgs', (req, res) => {
    if(util.auth(req,res)){
        // 关联查询用户的基础信息表
        const users = findAllUser();
        // 把我发出去的和发给我的查询出来
        const { id } = (req.session.userInfo.info || req.session.userInfo);
        
        chat.find({'$or': [{from: id}, {to: id}]}, (err, doc) => {
            if(!err){
                util.rtData(res, 200, doc, users);
            } else {
                util.rtData(res, 200, []);
            }
        });
    }
});


router.post('/setRead', (req, res) => {
    if(util.auth(req,res)){
        const { items } = req.body;
        const ids = items.split('-');

        chat.update({_id: {$in: ids}}, {isRead: true}, {multi: true}, (err, doc) => {
            if(!err && doc.nModified > 0){
                util.rtData(res, 200);
            } else {
                util.rtData(res, 1002);
            }
        });
    }
});

module.exports = router;